import storage from 'store'
import {ApiLogin, ApiCurrentUser, ApiLogout} from "/src/api/user.js"
import {ACCESS_TOKEN} from '@/store/mutation-types.js'
// import {apiGetPendingList} from "@/api/user.js";

const user = {
    state: {
        info: {},
        showNotice: true,
        sysNotice: {}
    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_SHOW_NOTICE: (state, value) => {
            state.showNotice = value
        },
        SET_INFO: (state, info) => {
            state.info = info
        },
        SET_NOTICE: (state, value) => {
            state.sysNotice[value[0]] = value[1]
        }
    },

    actions: {
        CloseNotice({commit}) {
            commit('SET_SHOW_NOTICE', false)
        },
        // 登录
        Login({commit}, data) {
            return new Promise((resolve, reject) => {
                ApiLogin(data).then(response => {
                    if (response.code !== 0) {
                        resolve(response)
                    } else {
                        storage.set(ACCESS_TOKEN, response['access_token'], 7 * 24 * 60 * 60 * 1000)
                        commit('SET_TOKEN', response['access_token'])
                        resolve(response)
                    }
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 获取用户信息
        async GetInfo({commit}) {
            return new Promise((resolve, reject) => {
                ApiCurrentUser().then(response => {
                    if (response.code != 0) {
                        reject('get user info failed ')
                    }
                    const result = response.data
                    commit('SET_INFO', result)
                    resolve(response)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 登出
        Logout({commit, state}) {
            return new Promise((resolve) => {
                ApiLogout(state.token).then(() => {
                    resolve()
                }).catch(() => {
                    resolve()
                }).finally(() => {
                    commit('SET_TOKEN', '')
                    storage.remove(ACCESS_TOKEN)
                })
            })
        },
    }
}

export default user
